package com.xyy.saas.payment.job.syncData;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.xyy.elasticjob.client.annotation.ElasticJobConf;
import com.xyy.saas.payment.service.PinganLoanService;
import com.xyy.saas.payment.trace.AlarmService;
import com.xyy.saas.payment.trace.DingTalkMessage;
import com.xyy.saas.payment.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@ElasticJobConf(name = "xyy.elastic.job.manage.PinganRepaymentPullJobAnaly", cron = "0 0 6 * * ?")
@Slf4j
public class PinganRepaymentPullJob implements SimpleJob {
    @Autowired
    private AlarmService alarmService;
    @Autowired
    private PinganLoanService pinganLoanService;

    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("PinganRepaymentPullJob#execute start");
        for (int i = 0; i < 3; i++) {
            try {
                // 解析账单
                pinganLoanService.downloadLoanHuanKuanFile(DateUtil.getToday2(), true);
                // 对账预警
                pinganLoanService.checkLoanAmount(true);
                break;
            } catch (Exception e) {
                log.error("PinganRepaymentPullJob#execute error：第{}次失败，error:{}", i + 1, e);
                if (i == 2) {
                    DingTalkMessage talkMessage = DingTalkMessage.builder()
                            .type("平安还款计划账单解析")
                            .method("job.syncData.PinganRepaymentPullJob.execute")
                            .msg("重试三次解析均异常：" + e.getMessage())
                            .param("请核实原因并调用接口：/downloadLoanHuanKuanFile?fileDate=" + DateUtil.getToday2() + "，重新进行解析")
                            .build();
                    alarmService.alarm(talkMessage);
                }
                try {
                    Thread.sleep(1000 * 60 * 10L);
                } catch (InterruptedException ex) { }
            }
        }
        log.info("PinganRepaymentPullJob#execute end");
    }

}
